import { connect } from 'dva';
import { createForm } from 'rc-form';
import { routerRedux } from 'dva/router';
import React, { Component, PropTypes } from 'react';
import { todayMonth, todayDate, GENDER } from 'const';
import { WingBlank, WhiteSpace, Flex, List, InputItem, DatePicker, Picker, Button, Modal, Toast, Checkbox } from 'antd-mobile';

const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const utcOffset = new Date(now.getTime() - (now.getTimezoneOffset() * 60000));
const { CheckboxItem, AgreeItem } = Checkbox;
const minDate = new Date(1900, 1, 1);
const maxDate = now;

const FamilyMemberPage = ({ dispatch, location, form, member,gender, ...rest }) => {
  // FamilyMemberPage 添加家庭成员列表的回调函数
  const { getFieldProps, setFieldsValue, validateFields, getFieldError } = form;
  const { state: { data }, pathname } = location;
  let iseditable = true;
  if (member.idNumber) {
    iseditable = false;
  }

  if(member.birthday){
      member.birthday = new Date(member.birthday);
  }else{
      member.birthday = '';
  }
  const saveMember = () => validateFields((errors, value) => {
    if (errors) {
      const fieldNames = Object.keys(errors);
      if (fieldNames[0]) {
        return Toast.fail(getFieldError(fieldNames[0]));
      }
    }

    value.gender = gender;
    
    let d = value.birthday;
    d = d.getFullYear() + '-' + todayMonth[(d.getMonth() + 1)] + '-' + todayDate[d.getDate()];
    value.birthday=d;

     // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
    let regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;  
    if(!regIdNo.test(value.idNumber)){  
        Toast.fail('身份证号填写有误');  
        return false;  
    }  

    if (pathname.indexOf('update') !== -1) {
      let modified = false;
      
      Object.keys(member).forEach((key, i) => {
        try {
          if (key === 'birthday') {
            member[key] = member[key].split(' ')[0];
          }
        } catch (e) { }

        const lowerKey = key.toLowerCase();
        if (value[lowerKey] && (value[lowerKey] !== member[key])) {
          modified = true;
        }
      });

      if (!modified) {
        return Toast.fail('请修改后再提交');
      }

      dispatch({
        type: 'family/updateMember',
        payload: { id: member.id, ...value },
      });
    }

    if (pathname.indexOf('add') !== -1) {
      dispatch({
        type: 'family/createMember',
        payload: value,
      });
    }
  });
  // 删除家庭成员的提示函数
  const deleteMember = () => Modal.alert('提示', '确定删除该家庭成员？', [  
    { text: '取消', onPress: () => { } },
    {
      text: '确定',
      onPress: () => dispatch({
        type: 'family/deleteMember',
        payload: member.id,
      }),
    },
  ]);

  const checkGender = (value) => {
    dispatch({ type: 'family/save', payload: { gender: value } });
  };

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <InputItem
          {...getFieldProps('name', {
            initialValue: member.name,
            validate: [{
              trigger: false,
              rules: [{ required: true, message: '请输入姓名' }],
            }],
          })}
          placeholder="请输入姓名"
        >姓名
        </InputItem>
        <InputItem 
          disabled={!iseditable}
          extra={GENDER.map(i => (
          <div style={{float: 'left'}} >
             <AgreeItem 
                checked = {gender === i.value} 
                onChange={() => checkGender(i.value)}>
                {i.label}
              </AgreeItem>
          </div>
          ))}
        ><div style={{color:'#3e3a39',fontSize: '0.28rem'}}>性别</div></InputItem>
        <DatePicker
          {...getFieldProps('birthday', {
            initialValue: member.birthday,
            validate: [{
              trigger: false,
              rules: [{ required: true, message: '请选择出生年月' }],
            }],
          })}
          mode="date"
          title="请选择"
          minDate={minDate}
          maxDate={maxDate}
          disabled={!iseditable}
        >
          <List.Item arrow="horizontal">出生年月</List.Item>
        </DatePicker>
        <InputItem
          {...getFieldProps('idNumber', {
            initialValue: member.idNumber,
            validate: [{
              trigger: false,
              rules: [{ required: true, message: '请输入身份证' }],
            }],
          })}
          placeholder="请输入身份证"
          disabled={!iseditable}
          type="string"
          maxLength={18}
        ><div style={{color:'#3e3a39',fontSize: '0.28rem'}}>身份证号</div>
        </InputItem>
        <InputItem
          {...getFieldProps('relation', {
            initialValue: member.relation,
            validate: [{
              trigger: false,
              rules: [{ required: true, message: '请输入关系' }],
            }],
          })}
          placeholder="请输入关系"
          disabled={!iseditable}
        ><div style={{color:'#3e3a39',fontSize: '0.28rem'}}>关系</div>
        </InputItem>
        <WhiteSpace size="xl" />
        <WingBlank>
          <Flex>
            {pathname.indexOf('update') !== -1 && member.patientId != member.familyId? (
                <Flex.Item>
                  <Button onClick={deleteMember}>删除</Button>
                </Flex.Item>
            ) : null}
            <Flex.Item>
              <Button type="primary" onClick={saveMember}>保存</Button>
            </Flex.Item>
          </Flex>
        </WingBlank>
        <WhiteSpace size="xl" />
      </List>
    </WingBlank>
  );
};

export default connect(({ family }) => ({ ...family }))(createForm()(FamilyMemberPage));
